package adger.me.yili.utils;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by heyue on 16/1/28.
 */
public class OkUtils {
    public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
    public static final int FailureFlag=0;
    public static final int ResponseFlag=1;
    public static OkHttpClient client = new OkHttpClient();

    public static void post(final Handler handler, String url, String json) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = Message.obtain();
                msg.what = FailureFlag;
                msg.obj = e;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = Message.obtain();
                msg.what = ResponseFlag;
                msg.obj = response;
                handler.sendMessage(msg);
            }
        });
    }

}
